<template>
  <div class="allsearch">
    <section class="search-content">
      <el-row :gutter="4" type="flex" justify="start">
        <el-col :span="24">
          <el-cascader
            :change-on-select="true"
            :options="courseCategorys"
            v-model="listQuery.courseType"
            :props="{value: 'id'}"
            @change="handleFilter"
          />
          <el-select v-model="listQuery.courseStatus" style="width:150px;" @change="handleFilter">
            <el-option
              v-for="item in options2"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
          <el-select v-model="listQuery.type" style="width:150px;" @change="handleFilter">
            <el-option
              v-for="item in options3"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
          <el-input
            v-model="listQuery.keyword"
            style="width:200px"
            placeholder="标题"
            @keyup.enter.native="handleFilter"
          />
          <el-input
            v-model="listQuery.author"
            style="width:200px"
            placeholder="创建者"
            @keyup.enter.native="handleFilter"
          />
          <el-button type="primary" size="medium" @click="handleFilter">搜索</el-button>
          <el-button size="medium" type="info" @click="clearParams">清空</el-button>
        </el-col>
      </el-row>
    </section>
    <el-dialog :visible.sync="dialogVisible" title="设置推荐课程" width="550px">
      <el-form ref="sequence" :model="sequence" :rules="rules">
        <el-form-item label="序号" label-width="120px" prop="num">
          <el-input v-model="sequence.num" style="width:280px;"/>
          <p style="margin:0">请输入长度不能超过8位的整数</p>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="updateOpenCourse">保存</el-button>
      </div>
    </el-dialog>
    <eltable
      :table-data="tableData.slice((currentpage-1)*pagesize,currentpage*pagesize)"
    >
      <el-table-column slot="first" :min-width="5" label="编号" prop="id" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.id }}</span>
        </template>
      </el-table-column>
      <el-table-column slot="second" :min-width="25" label="名称" prop="title" align="center">
        <template slot-scope="scope">
          <el-button type="text">{{ scope.row.title }}</el-button>
        </template>
      </el-table-column>
      <el-table-column slot="third" :min-width="25" label="状态" prop="title" align="center">
        <template slot-scope="scope">
          <el-button type="text">{{ scope.row.status | statusFilter }}</el-button>
        </template>
      </el-table-column>
      <el-table-column slot="isPro" :min-width="15" label="创建者" prop="creator" align="center">
        <template slot-scope="scope">
          <el-button type="text" @click="handleClickDialog(scope)">{{ scope.row.userName }}</el-button>
          <br>
          <span>{{ scope.row.createTimeStr }}</span>
        </template>
      </el-table-column>
      <el-table-column slot="button" :min-width="15" label="操作" prop="manage" align="center">
        <template slot-scope="scope">
          <el-dropdown
            type="primary"
            split-button
            trigger="click"
            @command="handleCommand($event,scope)"
          >管理
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item v-if="scope.row.recommended === 0" command="1">推荐课程</el-dropdown-item>
              <el-dropdown-item v-if="scope.row.recommended === 1" command="1">取消推荐</el-dropdown-item>
              <el-dropdown-item v-if="scope.row.status === 'draft'" command="2">发布课程</el-dropdown-item>
              <el-dropdown-item v-if="scope.row.status === 'published'" command="2">关闭课程</el-dropdown-item>
              <el-dropdown-item command="3">删除课程</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </template>
      </el-table-column>
    </eltable>
    <pagination
      :total="total"
      :current-page="currentpage"
      :page-size="pagesize"
      @handleSizeChange="handleSizeChange"
      @handleCurrentChange="handleCurrentChange"
    />
    <user-dialog
      :visiabledialog="userdialog"
      :dialog-data="dialogData"
      @changeVisiable="userdialog = false"
    />
  </div>
</template>

<script>
  import UserDialog from '@/components/Dialog'
  import Eltable from '@/components/Eltable'
  import Pagination from '@/components/Pagination' // 分页组件
  import {deleteOpenCourse, getOpenCourseList, updateOpenCourse} from '@/api/subject/openCourse' // 数据接口
  import {getCategoryList} from '@/api/subject/category'
  import {getUserDetail} from '@/api/operate/userDetail' // 数据接口
  import {getTenantId} from '@/utils/auth'

  export default {
    components: {
      Eltable,
      Pagination,
      UserDialog
    },
    filters: {
      statusFilter(status) {
        const statusMap = {
          draft: '未发布',
          published: '已发布',
          closed: '已关闭'
        };
        return statusMap[status]
      }
    },
    data() {
      return {
        userdialog: false,
        dialogData: {},
        dialogVisible: false,
        listQuery: {
          courseType: [],
          courseStatus: '',
          type: '',
          keyword: '',
          author: ''
        },
        total: 0,
        currentpage: 1,
        pagesize: 10,
        sequence: {
          entity: '',
          num: ''
        },
        courseCategorys: [],
        options2: [
          {
            label: '课程状态',
            value: ''
          },
          {
            label: '未发布',
            value: 'draft'
          },
          {
            label: '已发布',
            value: 'published'
          },
          {
            label: '已关闭',
            value: 'closed'
          }
        ],
        options3: [
          {
            label: '类型',
            value: ''
          },
          {
            label: '直播公开课',
            value: 'liveOpen'
          },
          {
            label: '普通公开课',
            value: 'open'
          }
        ],
        tableData: [],
        listFilter: [],
        rules: {
          num: [
            {required: true, message: '必填信息', trigger: 'blur'},
            {min: 1, max: 8, message: '长度不能超过8位', trigger: 'blur'},
            {pattern: /^[0-9]*[1-9][0-9]*$/, message: '请输入长度不能超过8位的整数'}
          ]
        }
      }
    },
    mounted() {
      this.getData();
      this.getCategoryList()
    },
    methods: {
      handleClickDialog(scope) {
        getUserDetail(scope.row.userId).then(response => {
          this.dialogData = response.data.item
        });
        this.userdialog = true
      },
      handleSizeChange(val) {
        console.log(val);
        this.currentpage = 1;
        this.pagesize = val.value;
        if (this.pagesize >= 20) {
          scrollTo(50, 800)
        }
      },
      handleCurrentChange(val) {
        console.log(val);
        this.currentpage = val.value;
        if (this.pagesize >= 20) {
          scrollTo(50, 800)
        }
      },
      handleFilter() {
        this.tableData = this.listFilter.filter(item => {
          if (this.listQuery.courseType[0] && item.categoryId !== this.listQuery.courseType[this.listQuery.courseType.length - 1]) return false;
          if (this.listQuery.courseStatus && item.status !== this.listQuery.courseStatus) return false;
          if (this.listQuery.type && item.type !== this.listQuery.type) return false;
          if (this.listQuery.keyword && item.title.toLowerCase().indexOf(this.listQuery.keyword.toLowerCase()) === -1) return false;
          if (this.listQuery.author && item.userName.toLowerCase().indexOf(this.listQuery.author.toLowerCase()) === -1) return false;
          return true
        });
        this.total = this.tableData.length
      },
      clearParams() {
        this.listQuery.courseType = [];
        this.listQuery.courseStatus = '';
        this.listQuery.type = '';
        this.listQuery.keyword = '';
        this.listQuery.author = '';
        this.getData()
      },
      getData() {
        getOpenCourseList(getTenantId()).then(response => {
          response.data.items.map(item => {
            if (item.createTime) item.createTimeStr = new Date(item.createTime).toLocaleString().substring(0, 10).replace(/[\u4e00-\u9fa5]/g, '')
          });
          this.tableData = response.data.items;
          this.total = response.data.items.length;
          this.listFilter = response.data.items
        })
      },
      cancelRecommend(scope) {
        this.$confirm(`确定取消推荐吗`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          scope.row.recommended = 0;
          scope.row.recommendedSeq = 100;
          scope.row.recommendedTime = '';
          updateOpenCourse(scope.row).then(() => {
            this.getData();
            this.$notify({
              title: '成功',
              message: '推荐已取消！',
              type: 'success',
              duration: 2000
            })
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '放弃取消推荐'
          })
        })
      },
      handleCommand(command, scope) {
        if (command === '1') {
          if (scope.row.recommended === 1) {
            this.cancelRecommend(scope)
          } else {
            this.dialogVisible = true;
            this.sequence.entity = scope.row
          }
        } else if (command === '2') {
          if (scope.row.status === 'draft') {
            scope.row.status = 'published'
          } else if (scope.row.status === 'published') {
            scope.row.status = 'closed'
          }
          updateOpenCourse(scope.row).then(() => {
            this.getData()
          })
        } else if (command === '3') {
          this.$confirm(`永久删除这个公开课吗`, '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            deleteOpenCourse(scope.row.id).then(response => {
              if (response.code === 200) {
                this.$notify({
                  title: '成功',
                  message: '公开课已被删除！',
                  type: 'success',
                  duration: 2000
                })
              }
              this.getData()
            })
          }).catch(() => {
            this.$message({
              type: 'info',
              message: '取消删除'
            })
          })
        }
      },
      updateOpenCourse() {
        this.$refs.sequence.validate((valid) => {
          if (valid) {
            this.dialogVisible = false;
            this.sequence.entity.recommended = 1;
            if (!this.sequence.num) this.sequence.num = 100;
            this.sequence.entity.recommendedSeq = this.sequence.num;
            this.sequence.entity.recommendedTime = new Date();
            updateOpenCourse(this.sequence.entity).then(() => {
              this.getData();
              this.$notify({
                title: '成功',
                message: '已成功推荐！',
                type: 'success',
                duration: 2000
              })
            })
          } else {
            console.log('error submit!!');
            return false
          }
        })
      },
      getCategoryList() {
        getCategoryList('course', getTenantId(),'0').then(response => {
          this.courseCategorys = response.data.items
        })
      }
    }
  }
</script>

<style lang="scss" scoped>
  .allsearch {
    margin-top: 0px;
    padding: 0;

    .search-content {
      width: 100%;
    }
  }
</style>
